package com.itxiaowu.controller;

import com.itxiaowu.constant.MessageConstant;
import com.itxiaowu.constant.RedisMessageConstant;
import com.itxiaowu.entity.Result;
import com.itxiaowu.utils.SMSUtils;
import com.itxiaowu.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validatecode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/sendMsg.do")
    public Result sendMsg(@RequestParam("telephone") String telephone){

        try{

            //1: 发送验证码
            // 1.1: 获得随机验证码
            String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
//            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code);

            System.out.println("验证码为:" + code);

            //2: 将数据封装到redis中
            Jedis jedis = jedisPool.getResource();
            jedis.setex(telephone + RedisMessageConstant.SENDTYPE_ORDER,2000,code);
            jedis.close();
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);

        }catch(Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

    }

    @RequestMapping("/sendlogin.do")
    public Result sendLog(@RequestParam("telephone") String telephone){
        try {
            // 1： 随机生成6位随机数
            Integer code = ValidateCodeUtils.generateValidateCode(6);

            // 2: 手机发送验证码
            String codeString = String.valueOf(code);
            //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone,codeString );

            System.out.println(" 验证码是:" + code);

            // 3: 将验证码封装到redis中
            Jedis jedis = jedisPool.getResource();
            jedis.setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN,60 * 3, codeString);

            // 4: 关闭资源
            jedis.close();

            // 5: 返回数据
            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
